package demo.job;

import demo.dao.AlertDao;
import demo.dao.AlertRuleDao;
import demo.dao.dto.AlertRule;
import demo.util.EnvironmentUtil;
import demo.util.PropertyUtil;
import demo.util.ConfigPropertyUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.List;

@Component
@EnableAsync // 2.开启多线程
public class TaskConfig {

    private static Logger logger = LoggerFactory.getLogger(TaskConfig.class);

    //@Value和@ConfigurationProperties 都是可以和@PropertySource组合使用的，只是注意配置的重复导致覆盖问题（后加载的会覆盖前面的）.
    @Value("${spring.application.name}")
    private String appName;

    @Autowired
    private AlertDao alertDao;

    @Autowired
    private AlertRuleDao alertRuleDao;

    @Autowired
    private Jedis jedis;

    @Autowired
    private DataSource ds1;

    @Scheduled(fixedRate = 1_000)
    public void job1() {
        logger.info("appName = {}", appName);

        List<AlertRule> list = alertRuleDao.selectAllActive();
        logger.info("AlertRule = {}", list);
    }

    @Scheduled(fixedRate = 1_000)
    public void job2() {
        try (Connection connection = ds1.getConnection();
             Statement statement = connection.createStatement();
             ResultSet resultSet = statement.executeQuery("select now()")) {
            if (resultSet.next()) {
                logger.info("now = {}", resultSet.getString(1));
            }
        } catch (Exception e) {
            logger.error("error = {}", e);
        }
    }


    public static void printProperty() {
        String name = EnvironmentUtil.getProperty("spring.application.name");
        logger.debug("name = {}", name);

        String url = EnvironmentUtil.getProperty("mongodb.galaxy.uri");
        logger.info("url = {}", url);

        String pass = ConfigPropertyUtil.getString("spring.redis.password");
        logger.warn("pass = {}", pass);

        String pass2 = PropertyUtil.getString("spring.redis.password");
        logger.error("pass2 = {}", pass2);
    }


}
